const { ipcMain, BrowserWindow } = require("electron");

const getSource = (url) => {
    return new Promise((resolve, reject) => {
        const win = new BrowserWindow({
            width: 500,
            height: 500,
            show: false,
            webPreferences: {
                offscreen: true,
            },
        });

        win.loadURL(url);

        const webContents = win.webContents;
        webContents.on("did-finish-load", async () => {
            const title = win.getTitle();
            try {
                const image = await webContents.capturePage();

                if (!image.isEmpty()) {
                    const screenshot = image.toDataURL();
                    resolve({
                        title,
                        screenshot,
                        url,
                    });
                } else {
                    resolve({
                        msg: "无法获取网站信息！"
                    });
                }

            } catch (e) {
                reject(e);
            }
        });
        //页面加载完之后再打开窗口
        // win.on("ready-to-show", () => {
        //     win.show()
        // });
    });
};
ipcMain.handle("on-url-event", async (e, url) => {
    const res = await getSource(url);
    return res;
});
